package com.derbysoft.synxisadapter.dswitch3.handler.impl;

import com.derbysoft.dswitch.dto.common.KeyValue;
import com.derbysoft.dswitch.remote.hotel.dto.HotelCancelRequest;
import com.derbysoft.dswitch.remote.hotel.dto.HotelCancelResponse;
import com.derbysoft.synxisadapter.commons.log.ReservationPair;
import com.derbysoft.synxisadapter.commons.log.TransactionLogger;
import com.derbysoft.synxisadapter.commons.model.OperationType;
import com.derbysoft.synxisadapter.commons.model.ReservationLog;
import com.derbysoft.synxisadapter.commons.model.TransactionLog;
import com.derbysoft.synxisadapter.dswitch3.handler.RemoteServiceHandler;
import com.derbysoft.synxisadapter.dswitch3.service.HotelProviderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import java.util.Date;

/**
 * User: jason
 * Date: 2012-11-21
 */
@Component("ds3CancelHandler")
public class CancelHandler extends AbstractHandler<HotelCancelRequest, HotelCancelResponse>
        implements RemoteServiceHandler<HotelCancelRequest, HotelCancelResponse> {

    @Autowired
    private HotelProviderService<HotelCancelRequest, HotelCancelResponse> ds3CancelService;

    @Override
    public HotelCancelResponse handle(HotelCancelRequest request) {

        TransactionLogger.getReservationLogger().set(createReservationLog(request.getHotelCancelRQ().getErsp()));

        TransactionLogger.getTransactionLogger().set(createTransactionLog());

        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        HotelCancelResponse response = ds3CancelService.execute(request);

        stopWatch.stop();
        long elapsedTime = stopWatch.getTotalTimeMillis();

        TransactionLogger.getTransactionLogger().get().setTimespan(elapsedTime);

        appendLogDetail(request, response);

        response.getElapsedTimes().add(new KeyValue(ElapsedTimeType.SYNXIS_ADAPTER.name(), String.valueOf(elapsedTime)));

        return response;
    }

    private ReservationPair createReservationLog(String ersp) {
        ReservationLog reservationLog = new ReservationLog();
        reservationLog.setOperationType(OperationType.CANCEL_RESERVATION);
        return new ReservationPair(ersp, reservationLog);
    }

    private TransactionLog createTransactionLog() {
        TransactionLog transactionLog = new TransactionLog();
        transactionLog.setTimestamp(new Date());
        transactionLog.setOperationType(OperationType.CANCEL_RESERVATION);
        return transactionLog;
    }
}
